/*
 * @# WholeCacheCase.java 2011-11-7 下午05:34:08
 * 
 * Copyright (C) 2010 - 2011 广州羿安信息科技有限公司
 * Guangzhou ianswer information technology co. ltd.
 * 
 * All rights reserved!
 */
package com.ianswer.experiments.redis;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;

/**
 * @author alvin hwang
 */
public class WholeCacheCase {
	
	private static final String HOST = "192.168.1.105";
	private static final int PORT = 6379;
	
	private static Logger log = LoggerFactory.getLogger(WholeCacheCase.class);
	
	private Jedis jedis;
	
	public WholeCacheCase() {
		JedisShardInfo shardInfo = new JedisShardInfo(HOST, PORT);
		jedis = new Jedis(shardInfo);
	}
	
	public void put(Long id) {
		NoneCacheCase noneCacheCase = new NoneCacheCase();
		RedisDemo data = noneCacheCase.get(id);
		
		Map<String, String> map = new HashMap<String, String>();
		map.put("name", data.getName());
		map.put("description", data.getDescription());
		map.put("age", String.valueOf(data.getAge()));
		
		jedis.hmset("redis-demo-" + data.getId(), map);
	}
	
	public RedisDemo get(Long id) {
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		
		Map<String, String> cache = jedis.hgetAll("redis-demo-" + id);
		
		RedisDemo data = new RedisDemo();
		data.setId(id);
		data.setName(cache.get("name"));
		data.setDescription(cache.get("description"));
		data.setAge(Integer.parseInt(cache.get("age")));
		
		stopWatch.stop();
		log.debug("WholeCacheCase get {} 运行时间为: {}", id, stopWatch.toString());
		
		return data;
	}
	
	public static void main(String[] args) {
		WholeCacheCase testcase = new WholeCacheCase();
		//testcase.put(1L);
		
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		
		int loops = 1000;
		for (int i = 0; i < loops; i++) {
			testcase.get(Long.valueOf(1));
		}
		
		stopWatch.stop();
		log.debug("WholeCacheCase get 遍历次数: {} 总运行时间为: {}", loops, stopWatch.toString());
	}
}
